import {Component, OnDestroy, OnInit} from '@angular/core';
import {OnlineUser} from "../../model/OnlineUser";
import {WebSocketSubject} from "rxjs/internal/observable/dom/WebSocketSubject";
import {webSocket} from "rxjs/webSocket";
import {delay, retryWhen, take} from "rxjs";

@Component({
  selector: 'app-imdashboard',
  templateUrl: './imdashboard.component.html',
  styleUrls: ['./imdashboard.component.css']
})
export class ImdashboardComponent implements OnInit ,OnDestroy{
  ul:Array<OnlineUser>;
  socket$: any;
  WS_ENDPOINT = "ws://192.168.2.66:2066/imdashboard";

  constructor() {
    this.ul=new Array<OnlineUser>()
  }

  ngOnInit(): void {

    this.init();
  }

  private async getNewWebSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.WS_ENDPOINT,
      deserializer:({data})=>{
        let ul=new Array<OnlineUser>();
        // console.log(data);
        ul=JSON.parse(data)
        return ul;
      }
      //closeObserver:(event:any)=>this.closeedConnect()
    });

  }


  init(){
    if (!this.socket$ || this.socket$.closed){
      this.getNewWebSocket()
        .then((data:any)=>{
          if(data){
            this.socket$=data;
            this.socket$
              .pipe(
                retryWhen(errors => errors.pipe(delay(1000), take(2))),
              )
              .subscribe((ul:Array<OnlineUser>)=>{
                //console.dir(m);

              this.ul=new Array<OnlineUser>();
              this.ul=ul


                // this.ml.push(m);
              })
          }
        })
    }
  }

  ngOnDestroy(): void {
    if(this.socket$!=null&&!this.socket$.closed){
      this.socket$.complete();
     
    }
  }

}
